import time
import subprocess
import re
import os
import sys
import uiautomator2 as u2

# import uiautomator2
# ===================== 路径配置 =====================
BASE_DIR = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
BIN_DIR = os.path.join(BASE_DIR, "bin")
ADB_PATH = os.path.join(BIN_DIR, "adb.exe")


# print(os.path.join(os.path.dirname(uiautomator2.__file__), "assets", "u2.jar"))


# ===================== 工具函数 =====================
def run_cmd(cmd):
    """运行命令并返回输出"""
    try:
        result = subprocess.run(cmd, capture_output=True, text=True)
        return result.stdout.strip()
    except Exception as e:
        print("执行命令失败:", cmd, e)
        return ""


def get_first_adb_device():
    """自动获取第一个 ADB 设备号"""
    try:
        result = run_cmd([ADB_PATH, "devices"])
        lines = result.strip().split("\n")[1:]
        devices = [line.split("\t")[0] for line in lines if "\tdevice" in line]
        if not devices:
            print("未检测到任何设备，请检查设备是否已连接")
        print(f"检测到设备: {devices[0]}")
        return devices[0]
    except Exception as e:
        pass


def connect_device(serial=None):
    """连接设备"""
    print(f"正在连接设备 {serial or '默认设备'}")
    d = u2.connect(serial)
    try:
        print(f"已连接设备: {d.serial}")
        if not check_device_model(serial):
            print("错误！此工具仅支持型号为 3576E 的设备，程序已退出。")
            sys.exit()
    except Exception as e:
        raise RuntimeError(f"设备连接失败: {e}")
    return d


def get_resolution(serial):
    """获取设备分辨率"""
    out = run_cmd([ADB_PATH, "-s", serial, "shell", "wm", "size"])
    match = re.search(r"Physical size:\s*(\d+x\d+)", out)
    if match:
        res = match.group(1)
        print(f"当前设备分辨率: {res}")
        return res
    print("未能获取分辨率")
    return None


def check_device_model(serial: str) -> bool:
    """判断设备型号是否为 3576E"""
    try:
        out = subprocess.check_output([ADB_PATH, "-s", serial, "shell", "getprop", "ro.product.model"],
                                      stderr=subprocess.STDOUT, text=True).strip()
        print(f"设备型号: {out}")
        return out == "3576E"
    except subprocess.CalledProcessError as e:
        print(f"执行 adb 命令失败: {e.output}")
        return False


def print_progress(step, total_steps):
    """打印带图标的进度条"""
    # percent = int(step / total_steps * 100)
    # bar_length = 20
    # filled_length = int(bar_length * step / total_steps)
    # bar = "🟩" * filled_length + "⬜" * (bar_length - filled_length)
    # print(f"⏳ [{bar}] {percent:3d}%")
    pass


def wait_for_text(d, text, timeout=5):
    """等待文本出现"""
    # print(f"⏳ 等待文字『{text}』出现 ...")
    if d(text=text).wait(timeout=timeout):
        # print(f"找到文字『{text}』")
        return True
    print(f"未找到文字『{text}』")
    return False


def click_by_text(d, text, timeout=5):
    """点击指定文字"""
    if wait_for_text(d, text, timeout):
        d(text=text).click()
        # print(f"🖱️ 点击『{text}』成功")
        time.sleep(0.5)
        return True
    return False


def input_screen_params(d, content: str):
    """设置屏参"""
    # print("⏳ 正在查找输入框 ...")
    edit = d(resourceId="android.app.smdt.apidemo:id/disp_set_params_et")
    if not edit.exists:
        print("未找到输入框节点")
        return False
    edit.click()
    time.sleep(0.3)
    edit.clear_text()
    btn = d(resourceId="android.app.smdt.apidemo:id/disp_set_params")
    if not btn.exists:
        print("未找到按钮「设置屏参」")
        return False
    # print(f"⌨️ 输入屏参内容（{len(content)} 字符）...")
    edit.set_text(content)
    time.sleep(0.5)
    btn.click()
    # print("✅ 屏参已输入并点击按钮成功")
    return True


def choose_screen_params():
    """让用户选择分辨率"""
    params = {
        "1": ("800x1280",
              "cpu_id=3576;disp_main=lvds;disp_aux=hdmi;lvds_x=1280;lvds_y=800;lvds_dclk_freq_khz=78000;"
              "lvds_hbp=100;lvds_hspw=44;lvds_hfp=100;lvds_vbp=8;lvds_vspw=20;lvds_vfp=6;"
              "lvds_fmt=0;lvds_reverse=0;lvds_lane_count=1;lvds_color_depth=8;"),
        "2": ("768x1366",
              "cpu_id=3576;disp_main=lvds;disp_aux=hdmi;lvds_x=1366;lvds_y=768;lvds_dclk_freq_khz=78000;"
              "lvds_hbp=100;lvds_hspw=44;lvds_hfp=100;lvds_vbp=8;lvds_vspw=20;lvds_vfp=6;"
              "lvds_fmt=0;lvds_reverse=0;lvds_lane_count=1;lvds_color_depth=8;"),
        "3": ("900x1600",
              "cpu_id=3576;disp_main=lvds;disp_aux=hdmi;lvds_x=1600;lvds_y=900;lvds_dclk_freq_khz=107000;"
              "lvds_hbp=220;lvds_hspw=20;lvds_hfp=100;lvds_vbp=16;lvds_vspw=1;lvds_vfp=10;"
              "lvds_fmt=1;lvds_reverse=0;lvds_lane_count=2;lvds_color_depth=8;"),
        "4": ("1080x1920",
              "cpu_id=3576;disp_main=lvds;disp_aux=;lvds_x=1920;lvds_y=1080;lvds_dclk_freq_khz=148500;"
              "lvds_hbp=100;lvds_hspw=20;lvds_hfp=160;lvds_vbp=25;lvds_vspw=10;lvds_vfp=10;"
              "lvds_fmt=0;lvds_reverse=0;lvds_lane_count=2;lvds_color_depth=8;"),
    }

    print("请选择要设置的屏幕分辨率：")
    for k, (name, _) in params.items():
        print(f"  {k}. {name}")
    while True:
        choice = input("输入编号选择（1-4）：").strip()
        if choice in params:
            name, value = params[choice]
            return name, value
        print("⚠输入无效，请重新输入（1~4）")


def wait_for_reboot(serial):
    """等待设备重启上线"""
    print("正在等待设备重启 ...")
    while True:
        time.sleep(3)
        out = run_cmd([ADB_PATH, "-s", serial, "get-state"])
        if "device" in out:
            print("设备已重新上线")
            break


def restart_settings_app(serial):
    """杀掉并重启设置应用"""
    run_cmd([ADB_PATH, "-s", serial, "shell", "am", "force-stop", "android.app.smdt.smdtsettings"])
    time.sleep(1)
    run_cmd([
        ADB_PATH, "-s", serial, "shell", "monkey", "-p",
        "android.app.smdt.smdtsettings", "-c", "android.intent.category.LAUNCHER", "1"
    ])
    time.sleep(3)


def main():
    serial = get_first_adb_device()
    if not serial:
        sys.exit()
    d = connect_device(serial)
    get_resolution(serial)
    target_name, screen_params = choose_screen_params()
    # 初始化
    print("正在设置屏参 ...")
    restart_settings_app(serial)

    total_steps = 5
    step = 1
    if click_by_text(d, "测试工具"):
        print_progress(step, total_steps)
    step += 1
    if click_by_text(d, "API 测试"):
        print_progress(step, total_steps)
    step += 1
    if click_by_text(d, "显示管理"):
        print_progress(step, total_steps)
    step += 1
    if wait_for_text(d, "设置屏参", timeout=8):
        print_progress(step, total_steps)
        input_screen_params(d, screen_params)
        step += 1
        print_progress(step, total_steps)
    else:
        print("未进入设置屏参界面")
    time.sleep(1)
    print("设置屏参完成，正在重启设备")
    run_cmd([ADB_PATH, "-s", serial, "reboot"])
    wait_for_reboot(serial)

    print("重新连接设备 ...")
    time.sleep(3)
    d = connect_device(serial)
    new_res = get_resolution(serial)

    print("目标分辨率:", target_name)
    print("当前分辨率:", new_res)

    if new_res == target_name:
        print("分辨率切换成功")
    else:
        print("切换失败，请重新切换")


if __name__ == "__main__":
    main()
    input()
